package com.elitel.frame.business.service.impl;

import com.elitel.frame.business.dao.ext.ExecuteSqlMapper;
import com.elitel.frame.business.service.AcFilterStationPushService;
import com.elitel.frame.main.entity.AcFilterStation;
import com.elitel.frame.main.entity.CfgDb;
import com.elitel.frame.main.entity.constant.DictionaryConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author hi_bj
 */
@Service
public class AcFilterStationPushServiceImpl implements AcFilterStationPushService {
    private static final Logger logger = LoggerFactory.getLogger(AcFilterStationPushServiceImpl.class);

    @Autowired
    private ExecuteSqlMapper executeSqlMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int save(CfgDb cfgdb, String serviceId, String appCode, List<AcFilterStation> acFilterStationList) {

        try {
            String validateTableExist = "SELECT COUNT(1) FROM AC_FILTER_STATION WHERE 1=2";
            executeSqlMapper.executequerySql(validateTableExist);
        } catch (Exception e) {
            logger.info("表或试图不存在或连接失败");
            //如果表不存在 尝试创建表
            executeSqlMapper.executequerySql(getCreateTableSQL(cfgdb.getDbVersion()));
        }
        //1.删除旧数据
        String[] appCodes = appCode.split(",");
        for (String code : appCodes) {
            StringBuilder deleteSql = new StringBuilder("DELETE FROM AC_FILTER_STATION WHERE SERVICE_ID='");
            deleteSql.append(serviceId).append("' AND APP_CODE = '").append(code).append("'");
            executeSqlMapper.deleteAction(deleteSql.toString());
        }
        // 2.插入新数据
        if (ObjectUtils.isEmpty(acFilterStationList)){
            return 0;
        }
        int result = 0;
        for (AcFilterStation acFilterStation : acFilterStationList) {
            StringBuilder insertSql = new StringBuilder("INSERT INTO AC_FILTER_STATION (DATA_ID, SERVICE_ID, APP_CODE, STCD) VALUES(");
            insertSql.append("'").append(acFilterStation.getDataId()).append("'");
            insertSql.append(",'").append(serviceId).append("'");
            insertSql.append(",'").append(acFilterStation.getAppCode()).append("'");
            insertSql.append(",'").append(acFilterStation.getStcd()).append("'");
            insertSql.append(")");
            result += executeSqlMapper.executeAction(insertSql.toString());
        }
        return result;
    }

    /**
     * 获取创建表SQL
     * @param databaseType 数据库类型
     * @return
     */
    private String getCreateTableSQL(String databaseType) {
        StringBuilder sb = new StringBuilder("CREATE TABLE ac_filter_station(");
        if (DictionaryConstant.DatabaseType_ORACLE.equals(databaseType)) {
            return sb.append("    data_id VARCHAR2(50) NOT NULL,")
                    .append("    service_id VARCHAR2(50),")
                    .append("    app_code VARCHAR2(50),")
                    .append("    stcd VARCHAR2(50),")
                    .append("    PRIMARY KEY (data_id)")
                    .append(")")
                    .toString();
        } else {
            //PostgreSQL  MySQL
            return sb.append("    data_id VARCHAR(50) NOT NULL,")
                    .append("    service_id VARCHAR(50),")
                    .append("    app_code VARCHAR(50),")
                    .append("    stcd VARCHAR(50),")
                    .append("    PRIMARY KEY (data_id)")
                    .append(")")
                    .toString();
        }
    }
}
